package com.fei.wechat.middlewar.service.impl.admin;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.fei.wechat.common.model.vo.PagerVo;
import com.fei.wechat.common.util.ObjectUtils;
import com.fei.wechat.middlewar.api.admin.IOperateLogService;
import com.fei.wechat.middlewar.dao.admin.IOperateLogDao;
import com.fei.wechat.middlewar.mode.bo.admin.OperateLogBo;
import com.fei.wechat.middlewar.mode.entity.admin.OperateLog;

/**
 * 描述: 操作日志接口实现层
 * 版权: Copyright (c) 2018 
 * 公司: 飞翔科技有限公司
 * 作者: 张进飞 
 * 版本: 1.0 
 * 创建日期: 2018年4月17日 
 * 创建时间: 上午8:42:56
 */
public class OperateLogServiceImpl implements IOperateLogService
{
    
    @Autowired
    private IOperateLogDao operateLogDao;
    
    @Override
    public void saveOperateLog(String moduleName, String function, String loginName, String hostIp, int operateType, String operateContentTemplate, Object[] args, String batchDetial)
    {
        String operateDetails = fillStringByArgs(operateContentTemplate, args);
        OperateLog log = new OperateLog();
        log.setHostIp(hostIp);
        log.setModule(moduleName);
        log.setOperateContent(operateDetails);
        log.setOperateType(operateType);
        log.setFunction(function);
        log.setOperateDate(new Date());
        log.setLoginName(loginName);
        if (StringUtils.isNotBlank(operateDetails) && StringUtils.isNotBlank(batchDetial))
        {
            log.setOperateDetails(operateDetails + batchDetial);
        }
        operateLogDao.saveOperateLog(log);
    }
    
    @Override
    public PagerVo<OperateLog> getPageLog(OperateLogBo operateLogBo) throws Exception
    {
        Map<String, Object> params = ObjectUtils.objectToMap(operateLogBo);
        int total = operateLogDao.getOperateLogCount(params);
        PagerVo<OperateLog> pager = new PagerVo<OperateLog>(operateLogBo.getCurrentPage(), operateLogBo.getPageSize(), total);
        int start = pager.getStart();
        int size = pager.getSize();
        params.put("start", start);
        params.put("size", size);
        List<OperateLog> list = operateLogDao.getOperateLogByPage(params);
        pager.setData(list);
        return pager;
    }
    
    private static String fillStringByArgs(String str, Object[] arr)
    {
        Matcher m = Pattern.compile("\\{(\\d)\\}").matcher(str);
        while (m.find())
        {
            str = str.replace(m.group(), arr[Integer.valueOf(m.group(1))].toString());
        }
        return str;
    }
}
